import axios from "axios";
import { ToastBottom, LogOut, getObj } from "@/utils/index";
import qs from "qs";
import Store from "@/store/index";
import { ElMessage, ElLoading } from "element-plus";

axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8";

//自定义实例默认值
const instance = axios.create({
  baseURL: "/zhonghang",
  timeout: 5000,
});
let loadingInstance;
// 请求拦截器
instance.interceptors.request.use(
  config => {
    // Store.commit("show");
    loadingInstance = ElLoading.service();
    config.data = qs.stringify({ ...config.data });
    return config;
  },
  error => {
    // Store.commit("hide");
    loadingInstance.close();
    return Promise.reject(error);
  }
);
// 响应拦截器
instance.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.status < 0) {
      // Store.commit("hide");
      loadingInstance.close();
      ElMessage.error(res.info);
      return;
    }
    if (Number(res.status) === 9999) {
      console.log(res.info);
      // Store.commit("hide");
      loadingInstance.close();
      return;
    }
    loadingInstance.close();
    // Store.commit("hide");
    return res;
  },
  error => {
    console.log("err" + error); // for debug
    // Store.commit("hide");
    loadingInstance.close();
    return Promise.reject(error);
  }
);

export default instance;
